package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.concurrent.*;

/**
 *
 * 使用FutureTask优化串行操作：
 // 向电商S1询价，并保存
 r1 = getPriceByS1();
 save(r1);
 // 向电商S2询价，并保存
 r2 = getPriceByS2();
 save(r2);
 // 向电商S3询价，并保存
 r3 = getPriceByS3();
 save(r3);
 */
public class _11_ThreadPool_FutureTask {

    public static void main(String[] args) {
        final ThreadPoolExecutor pool
                = new ThreadPoolExecutor(2,
                2,
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(20));

        FutureTask<Integer> task1 = new FutureTask<>(() -> getPriceByS1());
        FutureTask<Integer> task2 = new FutureTask<>(() -> getPriceByS2());
        FutureTask<Integer> task3 = new FutureTask<>(() -> getPriceByS3());
        pool.execute(task1);
        pool.execute(task2);
        pool.execute(task3);
        try {
            Integer price = task1.get();
            save(price);
            price = task2.get();
            save(price);
            price = task3.get();
            save(price);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        pool.shutdown();
    }

    private static void save(int price) {
        // save
    }

    private static int getPriceByS1() {
        try {
            Thread.sleep(ThreadLocalRandom.current().nextInt(100, 1200));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 10;
    }
    private static int getPriceByS2() {
        try {
            Thread.sleep(ThreadLocalRandom.current().nextInt(100, 1200));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 15;
    }
    private static int getPriceByS3() {
        try {
            Thread.sleep(ThreadLocalRandom.current().nextInt(100, 1200));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 12;
    }
}
